package timing.ukulele.storage.util;

import org.springframework.data.mongodb.core.query.Update;

import java.lang.reflect.Field;

public final class UpdateUtil {
    /**
     * 获取实体中的更新信息
     *
     * @param entity 要更新的实体
     * @param <T>    实体类型
     * @return
     * @throws IllegalAccessException
     */
    public static <T> Update getUpdateValues(T entity) throws IllegalAccessException {
        Update update = new Update();
        Field[] declaredFields = entity.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            String name = declaredField.getName();
            if (name.equalsIgnoreCase("id"))
                continue;
            declaredField.setAccessible(true); // 私有属性必须设置访问权限
            Object value = declaredField.get(entity);
            if (value == null)
                continue;
            update.set(name, value);
        }
        return update;
    }
}
